from flask import render_template,request,jsonify
from app import db
from . import cms_link
from .model import Link
import json
import uuid

#将查询出的list数据转换为字典，否则无法序列化
def to_dict(items):
    lic = []
    for item in items:
        lic.append(
            {
                'link_pk': item.link_pk,
                'link_title': item.link_title,
                'link_images': item.link_images,
                'link_address': item.link_address,
                'link_remarks': item.link_remarks
            }
        )
    return lic


@cms_link.route('/index')
def index():
    return render_template("pages/cms/link/index.html")


@cms_link.route('/edit')
def edit():
    return render_template("pages/cms/link/edit.html")


@cms_link.route('/saveOrUpdate',methods=['GET','POST'])
def save():
        if request.method == 'POST':
            # link_pk = uuid.uuid1()
            link_title = request.form.get('link_title', None)
            link_images = request.form.get('link_images', None)
            link_address = request.form.get('link_address', None)
            link_remarks = request.form.get('link_remarks', None)

            newobj = Link()
            # newobj.link_pk=link_pk
            newobj.link_title = link_title
            newobj.link_images = link_images
            newobj.link_address = link_address
            newobj.link_remarks = link_remarks
            db.session.add(newobj)
            db.session.commit()
        data = {
            'state':'success',
            'msg':'添加成功'
        }
        return json.dumps(data)


# 进行分页查询
@cms_link.route('/pages',methods=['GET','POST'])
def pages():
    if request.method == "POST":
        page = request.form.get("page") #获取页码
    else:
        page = request.args.get("page")
    pages = Link.query.paginate(int(page), 30, False) #flask_sqlalchemy提供分页方法.paginate
    # db.session.close()
    #将分页对象组装为需要的数据
    data = {
        'msg':'success',
        'code':0,
        'data':to_dict(pages.items),
        'count':pages.total
    }
    print(pages.items)
    return json.dumps(data,ensure_ascii=False)
    # return jsonify(data)







